import axios from 'axios';
import qs from 'qs' ;

let utils = {
	
	getToken:function() {
		let user = JSON.parse(sessionStorage.getItem("user")) ;
		let token = ( user == null || user.token == null)?null:user.token ;
		return token ;
	},
	url_token:function(url) {
	
		let token = this.getToken() ;
	    if (url.indexOf("?") != -1) {
	        url += '&token=' + token;
	    } else {
	        url += '?token=' + token;
	    }
		return  url ;	
	} ,
	get:function( url, config ) { 
	
		let newUrl = this.url_token( url ) ;
		return axios.get( newUrl ).then((res) => {
			return res ;  
		});
	},
	get:function( url, params, config ) { 
	
		let newUrl = this.url_token( url ) ;
		if ( params != null && params != undefined )
		{
			if (newUrl.indexOf("?") != -1) {
		        newUrl += '&' + qs.stringify(params);
		    } else {
		        newUrl += '?' + qs.stringify(params);
		    }
	   	}
		return axios.get( newUrl ).then((res) => {
			return res ;  
		});
	},
	delete:function( url, config ) { 
	
		let newUrl = this.url_token( url ) ;

		return axios.delete( newUrl, config ).then((res) => {
			return res ;  
		});
	},
	head:function( url, config ) { 
	
		let newUrl = this.url_token( url ) ;
		return axios.head( newUrl, config ).then((res) => {
			return res ;  
		});
	},
	options:function( url, config ) { 
	
		let newUrl = this.url_token( url ) ;
		return axios.options( newUrl, config ).then((res) => {
			return res ;  
		});
	},
	post:function( url, params, config ) { 
		
		/**
		if ( params != null && params.length>0 ) {
			params += ("&token="+this.getToken()) ;
		} else {
			params += ("token="+this.getToken()) ;
		}
		*/
		let newUrl = this.url_token( url ) ;
		return axios.post( newUrl, params, config ).then((res) => {
			return res ; 
		});
	},
	put:function( url, params, config ) { 
	
		let newUrl = this.url_token( url ) ;
		return axios.put( newUrl, params, config ).then((res) => {
			return res ; 
		});
	},
	
};



export default utils;